<?php
namespace app\common\model;

/**
 * 优惠券用户领取模型
 */
class CouponUser extends BaseModel
{
    // 定义表名
    protected $name = 'coupon_user';
    // 定义主键
    protected $pk = 'coupon_user_id';
    // 追加字段
    protected $append = [];
    
    /**
     * 关联用户表
     */
    public function user()
    {
        return $this->belongsTo('app\\common\\model\\User','user_id');
    }
    /**
     * 关联优惠券表
     */
    public function coupon()
    {
        return $this->belongsTo('app\\common\\model\\Coupon','coupon_id');
    }
    
    /**
     * 有效起始时间
     */
    public function getExpireStarAttr($value,$data)
    {
        return ['text' => date('Y-m-d',$data['expire_star']), 'value' => $value];
    }
    
    /**
     * 有效结束时间
     */
    public function getExpireEndAttr($value,$data)
    {
        return ['text' => date('Y-m-d',$data['expire_end']), 'value' => $value];
    }
    
    /**
     * 类型
     */
    public function getTypeAttr($value)
    {
        $status = [10 => '现金券', 20 => '折扣券', 30 => '赠送券'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 获取列表
     * $valid 是否有效可以使用的
     */
    public function getList($user_id = 0, $type = 0,$valid=true)
    {
        //删除3分钟后过期的优惠券
        $this->where('expire_end','<',time()-180)->delete();
        $model = $this->with(['coupon','user']);
        if($valid){
            //有效可以使用的
            $model->where('expire_star','<',time())->where('expire_end','>',time());
        }else{
            //所有得
            $model->where('expire_end','>',time());
        }
        //筛选
        $filter = [];
        $user_id > 0 && $filter['user_id'] = $user_id;
        $type > 0 && $filter['type'] = $type;
        // 排序规则
        $sort = [];
        $sort = ['expire_end' => 'asc','coupon_user_id' => 'desc'];//按照时间排序
        // 执行查询
        return $model->where($filter)->order($sort)->select()->toArray();
    }

    /**
     * 用户统计数量
     */
    public static function getUserCount($user_id = 0)
    {
        // 筛选条件
        $filter = [];
        $user_id > 0 && $filter['user_id'] = $user_id;
        $count = array();
        $count['all'] = self::where('expire_end','>',time())->where($filter)->count();
        $count['10'] = self::where('expire_end','>',time())->where($filter)->where('type',10)->count();
        $count['20'] = self::where('expire_end','>',time())->where($filter)->where('type',20)->count();
        $count['30'] = self::where('expire_end','>',time())->where($filter)->where('type',30)->count();
        $count['40'] = self::where('expire_end','>',time())->where($filter)->where('type',40)->count();
        return $count;
    }
}